// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import fse from 'fs-extra';
import path from 'path';

const CONFIG_FOLDER = '.vscode';
const CONFIG_FILENAME = 'ssh.config.json';
const CONFIG_PATH = path.join(CONFIG_FOLDER, CONFIG_FILENAME);
const TERMINAL_NAME = 'dd_vscode_terminal';

function getPath(): any {
	const workspaceFolders = vscode.workspace.workspaceFolders;
	if(!workspaceFolders) {return undefined;};
	return workspaceFolders[0].uri.fsPath;
}

function getConfig(): any {
	let configPath = getPath();
	if(!path) {
		vscode.window.showErrorMessage('没发现对应的ssh.config.js配置文件');
		return undefined;
	};
	configPath = path.join(configPath, CONFIG_PATH);
	if(!fse.existsSync(configPath)) {
		vscode.window.showErrorMessage('没发现对应的ssh.config.js配置文件');
		return undefined;
	};
	return fse.readJSONSync(configPath);
}

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
	const menu = vscode.commands.registerCommand('dd-ssh.connect', () => {
		let remoteConfig: any = getConfig(); 
		if(!remoteConfig) {return;};

		const terminals = vscode.window.terminals;
		const cur = terminals.filter(item => item.name === TERMINAL_NAME);
		const terminal = cur?.length !== 0 ? cur[0] : vscode.window.createTerminal({ name: TERMINAL_NAME });

		let sh = '';
		if(!remoteConfig?.username || !remoteConfig?.host) {return;};
		if(cur?.length === 0) {sh += `ssh ${remoteConfig.username}@${remoteConfig.host}`;}
		terminal.show();
		terminal.sendText(sh);

		//执行sh脚本
		if(Array.isArray(remoteConfig?.sh)) {
			remoteConfig?.sh?.forEach((item: string) => {
				terminal.sendText(item);
			});
		}
	});

	context.subscriptions.push(menu);
}

// This method is called when your extension is deactivated
export function deactivate() { }
